<?php

namespace app\admin\controller\commission;

use app\admin\model\Details;
use app\admin\model\Order;
use app\admin\model\User;
use app\common\controller\Backend;
use think\exception\DbException;
use think\Loader;
use think\response\Json;

/**
 * 佣金记录管理
 *
 * @icon fa fa-circle-o
 */
class Log extends Backend
{

    /**
     * Log模型对象
     * @var \app\admin\model\commission\Log
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\commission\Log;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */



    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        // 如果不是 Ajax 请求，返回视图
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }

        // 如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        // 接收前端传递的 realname
        $filter = $this->request->request('filter', '');
        $filterArr = (array)json_decode($filter, true);
        $realname = isset($filterArr['realname']) ? $filterArr['realname'] : null;
        $order_user_name = isset($filterArr['order_user_name']) ? $filterArr['order_user_name'] : null;
        // 获取其他过滤条件
        $filter = json_decode($this->request->get("filter", ''), true);
        $op = json_decode($this->request->get("op", '', 'trim'), true);

        // 如果存在 realname，进行相关处理
        if (isset($filter['realname'])) {
            unset($filter['realname'], $op['realname']);
        }
        if (isset($filter['order_user_name'])) {
            unset($filter['order_user_name'], $op['order_user_name']);
        }

        // 更新请求参数
        $this->request->get(['filter' => json_encode($filter, true)]);
        $this->request->get(['op' => json_encode($op, true)]);

        // 构建查询参数
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        // 初始化 userIds 数组
        $userIds = [];
        // 查询列表时使用 userIds 条件
        $query = $this->model->where($where); // 设置主查询条件
        // 如果提供了 realname，添加到独立的查询条件中
        if ($realname) {
            // 从 User 表查找
            $user = User::where('nickname', 'LIKE', '%' . $realname . '%')->select();
            $userIds = array_column($user, 'id'); // 提取 id

            // 如果没有查到，则从 Details 表查找
            if (empty($userIds)) {
                $details = Details::where('name', 'LIKE', '%' . $realname . '%')->select();
                $userIds = array_column($details, 'user_id'); // 提取 user_id
            }
            if (!empty($userIds)) {
                $query->whereIn('user_id', $userIds);
            }else{
                $query->whereIn('user_id', -1);
            }
        }
        $userIds1 = [];
        if ($order_user_name) {
            // 从 User 表查找
            $user = User::where('nickname', 'LIKE', '%' . $order_user_name . '%')->select();
            $userIds1 = array_column($user, 'id'); // 提取 id
            if (!empty($userIds1)) {
                $query->whereIn('order_user_id', $userIds1);
            }else{
                $query->whereIn('order_user_id', -1);
            }
        }



        // 如果 userIds 不为空，添加 whereIn 条件


        // 获取 paginated 列表
        $list = $query->order($sort, $order)->paginate($limit);

        // 遍历列表以补全用户姓名
        foreach ($list as $row) {
            if ($row['role'] == 'parent' || $row['role'] == 'parent2') {
                $details = User::where('id', '=', $row->user_id)->find();
                if ($details) {
                    $row->realname = $details['nickname'];
                }
            } elseif ($row['role'] == 'agent' || $row['role'] == 'platform' || $row['role'] == 'companion') {
                $details = Details::where('user_id', '=', $row->user_id)->find();
                if ($details) {
                    $row->realname = $details['name'];
                }
            }
        }

        // 返回结果
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }



}
